﻿using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace GitNet.WindowsApp.Models;

public class ProjectData
{
    public List<PathData>? PathData { get; set; }
    public string? UserName { get; set; }
    public string? Email { get; set; }

    public string? Account { get; set; }
    public string? Password { get; set; }


    public static ProjectData? OpenJson()
    {
        var jsonPath = "";
#if DEBUG
        jsonPath = Path.Combine(Coding.CodePath, "Assets", "data.json");
#else
        jsonPath = "data.json";
#endif
        if (File.Exists(jsonPath))
        {
            return JsonConvert.DeserializeObject<ProjectData>(File.ReadAllText(jsonPath));
        }

        File.WriteAllText(jsonPath,"{}");
        return null;
    }

    public static void Save(ProjectData data)
    {
        var json = JsonConvert.SerializeObject(data);
        var jsonPath = "";
#if DEBUG
        jsonPath = Path.Combine(Coding.CodePath, "Assets", "data.json");
#else
        jsonPath = "data.json";
#endif
        File.WriteAllText(jsonPath, json);
    }

    public static void Save(PathData data)
    {
        var openJson = OpenJson();
        if (openJson == null) return;
        openJson.PathData ??= new List<PathData>();
        var findLastIndex = openJson.PathData.FindLastIndex(x => x.RepositoryPath == data.RepositoryPath);
        if (findLastIndex < 0 || findLastIndex >= openJson.PathData.Count) openJson.PathData.Add(data);
        else openJson.PathData[findLastIndex] = data;
        Save(openJson);
    }

    public static void Remove(PathData data)
    {
        var openJson = OpenJson();
        if (openJson == null) return;
        openJson.PathData ??= new List<PathData>();
        var findLastIndex = openJson.PathData.FindLastIndex(x => x.RepositoryPath == data.RepositoryPath);
        if (findLastIndex < 0 || findLastIndex >= openJson.PathData.Count) return;
        openJson.PathData.RemoveAt(findLastIndex);
        Save(openJson);
    }
}